package com.xxxx.seckill.exception;


import com.xxxx.seckill.vo.RespBean;

import com.xxxx.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingRequestCookieException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
@Slf4j
public class GlobalException {

    @ExceptionHandler({BindException.class,MobileException.class})
    @ResponseBody
    public RespBean getException(Exception ex) {
        //异常1 ：
        if (ex instanceof BindException) {
            RespBean res = new RespBean(
                    RespBeanEnum.MOBILE_ERROR.getCode(),
                    RespBeanEnum.MOBILE_ERROR.getMessage(),
                    null);
            ex.printStackTrace();
            return res;

            //异常二
        } else {
            ex = (MobileException) ex;
            String value = ((MobileException) ex).getValue();
            RespBean res = new RespBean(
                    RespBeanEnum.MOBILE_ERROR.getCode(),
                    value,
                    value);
            ex.printStackTrace();
            return res;
        }

    }

    @ExceptionHandler(MissingRequestCookieException.class)
    public String getMissingRequestCookieException(MissingRequestCookieException ex){
        ex.printStackTrace();
        return "login";
    }

    @ExceptionHandler(CountFail.class)
    @ResponseBody
    public RespBean getCountFail(CountFail ex){
        ex.printStackTrace();
        String value = ex.getValue();
        if (value == null){
        return RespBean.error(RespBeanEnum.COUNT_FAIL);
        }
        return RespBean.error(RespBeanEnum.NO_REPEATED);
    }
}
